import mapboxgl from "mapbox-gl";

export class MapCompare {
  constructor(map, tiandituLayer) {
    this.map = map;
    this.compareMap = null;
    this.tiandituLayer = tiandituLayer;
    this.isSyncing = false;
    this.moveHandler = null;
    this.compareMapMoveHandler = null;
  }

  // 初始化对比地图
  initCompareMap() {
    if (!this.map) return;

    // 创建右侧地图（影像地图）
    this.compareMap = new mapboxgl.Map({
      container: "after",
      style: {
        version: 8,
        sources: {},
        layers: [],
      },
      center: [this.map.getCenter().lng, this.map.getCenter().lat],
      zoom: this.map.getZoom(),
      maxZoom: 17,
      minZoom: 6,
    });

    this.compareMap.on("load", () => {
      // 设置右侧地图样式为影像图
      this.tiandituLayer.switchMapStyle(this.compareMap, "vec");
    });

    // 绑定同步事件
    this.bindSyncEvents();
  }

  // 同步地图视角
  syncMaps(sourceMap, targetMap) {
    if (!targetMap || this.isSyncing) return;
    this.isSyncing = true;
    
    try {
      targetMap.setCenter([sourceMap.getCenter().lng, sourceMap.getCenter().lat]);
      targetMap.setZoom(sourceMap.getZoom());
      targetMap.setBearing(sourceMap.getBearing());
      targetMap.setPitch(sourceMap.getPitch());
    } catch (error) {
      console.error('同步地图视角失败:', error);
    } finally {
      setTimeout(() => {
        this.isSyncing = false;
      }, 0);
    }
  }

  // 绑定同步事件
  bindSyncEvents() {
    this.moveHandler = () => this.syncMaps(this.map, this.compareMap);
    this.compareMapMoveHandler = () => this.syncMaps(this.compareMap, this.map);
    
    this.map.on("move", this.moveHandler);
    this.compareMap.on("move", this.compareMapMoveHandler);
  }

  // 移除对比地图
  removeCompareMap() {
    if (!this.compareMap) return;
    
    // 移除事件监听
    if (this.moveHandler) {
      this.map.off("move", this.moveHandler);
      this.moveHandler = null;
    }
    if (this.compareMapMoveHandler) {
      this.compareMap.off("move", this.compareMapMoveHandler);
      this.compareMapMoveHandler = null;
    }

    // 移除地图实例
    this.compareMap.remove();
    this.compareMap = null;
  }

  // 重新计算地图大小
  resize() {
    this.isSyncing = true;
    this.map.resize();
    this.compareMap?.resize();
    setTimeout(() => {
      this.isSyncing = false;
    }, 0);
  }

  // 获取对比地图实例
  getCompareMap() {
    return this.compareMap;
  }
} 